package cn.huiyunche.base.service.schedule;

import cn.huiyunche.base.service.constant.App;
import cn.huiyunche.base.service.enums.SServiceOrderStatusEnum;
import cn.huiyunche.base.service.enums.WayBillQuoteStatusEnum;
import cn.huiyunche.base.service.framework.redis.MindsJedisConnectionFactory;
import cn.huiyunche.base.service.interfaces.SOrderService;
import cn.huiyunche.base.service.mappers.SOrderMapper;
import cn.huiyunche.base.service.mappers.SWaybillQuoteMapper;
import cn.huiyunche.base.service.model.SOrder;
import cn.huiyunche.base.service.model.SWaybillQuote;
import cn.huiyunche.base.service.model.SWaybillQuoteExample;
import cn.huiyunche.tools.basic.Collections3;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

/**
 * @ClassName: OrderSchedule
 * @Description: 订单相关定时任务
 * @author: Aaron
 * @date: 2016年6月28日 下午5:03:38
 */
@Service
public class OrderSchedule {
    private static final Logger logger = LoggerFactory.getLogger(OrderSchedule.class);

    @Autowired
    private MindsJedisConnectionFactory connectionFactory = null;
    @Autowired
    private SOrderService orderService = null;
    @Autowired
    private SOrderMapper orderMapper = null;
    @Autowired
    private SWaybillQuoteMapper quoteMapper = null;

    public SWaybillQuoteMapper getQuoteMapper() {
        return quoteMapper;
    }

    private MindsJedisConnectionFactory getConnectionFactory() {
        return this.connectionFactory;
    }

    public SOrderService getOrderService() {
        return orderService;
    }

    public SOrderMapper getOrderMapper() {
        return orderMapper;
    }

    /**
     * 清除过期的发布的订单
     *
     * @return
     */


//  @Scheduled(fixedRate=60000)
    public void doRedisCleanJob() {
        logger.info("OrderSchedule.doRedisCleanJob start...");
        String orderPubKey = App.OrderPublishOrderidsKey;
        Jedis jedis = this.getConnectionFactory().fetchJedisConnector();
        try {
            HashMap<String, String> hashMap = (HashMap<String, String>) jedis.hgetAll(orderPubKey);
            if (!Collections3.isEmpty(hashMap)) {
                for (Entry<String, String> entry : hashMap.entrySet()) {
                    Long orderid = Long.parseLong(entry.getKey());
                    Date publishTime = new Date(Long.parseLong(entry.getValue()));
                    SOrder order = this.getOrderMapper().selectByPrimaryKey(orderid);
                    if (order != null) {
                        // 时间超过2小时
                        if ((publishTime.getTime() + App.ORDER_EFFECTIVE_TIME * 1000) <= new Date().getTime()) {
                            jedis.hdel(orderPubKey, orderid.toString());
                            // 超时发布订单取消
                            this.getOrderService().updateStatus(order.getId(),
                                    SServiceOrderStatusEnum.CANCELED.getValue(), 0, true);

                            // 所有报价作废
                            SWaybillQuoteExample search = new SWaybillQuoteExample();
                            search.createCriteria().andOrderIdEqualTo(order.getId());
                            List<SWaybillQuote> quotes = this.getQuoteMapper().selectByExample(search);
                            if (CollectionUtils.isNotEmpty(quotes)) {
                                for (int i = 0; i < quotes.size(); i++) {
                                    SWaybillQuote quote = quotes.get(i);
                                    quote.setStatus(WayBillQuoteStatusEnum.ABANDONED.getValue());// 作废
                                    this.getQuoteMapper().updateByPrimaryKeySelective(quote);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("OrderSchedule.doRedisCleanJob : ", e);
            throw new BusinessException("Redis删除订单失败！");
        } finally {
            jedis.close();
        }
        logger.info("OrderSchedule.doRedisCleanJob end...");
    }

}
